﻿using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataCodeDemo.Operators
{
    public class HalconOperator
    {
        public static DataCodeResult FindDataCode(HImage hImage, string dmPath,FindParams findParams)
        {            
            HDataCode2D hDataCode2D = new HDataCode2D(dmPath);
            HImage imageIlluminate = hImage.Rgb1ToGray().Illuminate(107, 107, 0.7);
            HRegion hRegionThreshold = imageIlluminate.Threshold(177.0, 255.0);
            HRegion hRegionFindSq = hRegionThreshold.ErosionCircle(2.0).//开运算消除噪点
                ClosingCircle(findParams.SqClosingRedius).//闭运算膨胀有效区域
                FillUp().//填充
                Connection().//分割
                SelectShape("area", "and", findParams.SqMinArea, 1000000).//选择面积满足条件的区域
                DilationRectangle1(findParams.SqExpansion, findParams.SqExpansion).//膨胀该区域包容所有点阵
                ShapeTrans("rectangle2");//变换该区域为旋转矩形
            HRegion hRegionPoints = hRegionThreshold.Connection().//分割
                Intersection(hRegionFindSq).//与点阵区域相交
                Union1().//联合
                DilationRectangle1(findParams.PointExpansion, findParams.PointExpansion);//膨胀点阵
            HImage hImagePaint = hRegionPoints.PaintRegion(imageIlluminate, 0.0, "fill").//在图上画出点阵黑点
                PaintRegion(hRegionPoints.Complement(), 255.0, "fill");//其它地方涂白
            HXLDCont hXLDCont = hDataCode2D.FindDataCode2d(hImagePaint, "stop_after_result_num", findParams.FindNum, out HTuple resultHandles, out HTuple decodedDataStrings);

            if (hXLDCont.CountObj() < 1)
            {
                hXLDCont = hDataCode2D.FindDataCode2d(hImagePaint, "train", "all", out resultHandles, out decodedDataStrings);
                if (hXLDCont.CountObj() > 0)
                {
                    hDataCode2D.WriteDataCode2dModel(dmPath);
                    
                }               
            }
            hDataCode2D?.Dispose();
            imageIlluminate?.Dispose();
            hRegionThreshold?.Dispose();
            hRegionFindSq?.Dispose();
            hRegionPoints?.Dispose();
            hImagePaint?.Dispose();
        
            return new DataCodeResult { HXLDConts = hXLDCont, DecodedDataStrings = decodedDataStrings };
        }
    }
    public class DataCodeResult:IDisposable
    {
        public HXLDCont HXLDConts { get; set; }
        public HTuple DecodedDataStrings { get; set; }

        public void Dispose()
        {
            HXLDConts?.Dispose();
            DecodedDataStrings = null;
        }
    }
}
